package ee.ts022.tuum.controllers;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.JmsException;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import ee.ts022.tuum.services.jms.JmsPostProcessor;

@Controller
public class RestController {
	private static final Logger logger = LoggerFactory.getLogger(RestController.class);

	@Autowired
	private JmsTemplate jmsTemplate;

	@RequestMapping(value = "rest/contracts/{customerId}", method = RequestMethod.GET, produces="application/json")
	public @ResponseBody String getContracts(@PathVariable String customerId) {

		String correlationId = UUID.randomUUID().toString();
		
		Map<String, String> request = new HashMap<String, String>();
		request.put("action", "getCustomerContracts");
		request.put("customerId", customerId);

		try {
			jmsTemplate.convertAndSend(request, new JmsPostProcessor(correlationId));
		} catch (JmsException e) {
			logger.error(e.getMessage());
		}
		
		String JSONresult = "[]";
		try {
			jmsTemplate.setReceiveTimeout(10000);
			String response = (String) jmsTemplate.receiveAndConvert(correlationId);
			JSONresult = (response != null ? response : "[]");
		} catch (JmsException e) {
			logger.error(e.getMessage());
		}

		return JSONresult;
	}

}
